package sapling.web.admin;


import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import sapling.dao.AdminDao;
import sapling.dao.CompanyDao;
import sapling.dao.RoleDao;
import sapling.form.LoginForm;
import sapling.model.Admin;
import sapling.model.Company;
import sapling.model.Role;
import sapling.service.TreeService;
import sapling.utils.Md5Util;

import javax.annotation.PostConstruct;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created by wuzh on 2016/12/13.
 */
@Controller
@Slf4j
public class LoginAction {
    @Autowired
    private AdminDao adminDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private CompanyDao companyDao;

    @PostConstruct
    public void userInit() {
        Company company=companyDao.findOneByName("集团总部");
        if(Objects.isNull(company)){
            company=new Company();
        }
        company.setPersonPhone("1234567");
        company.setName("集团总部");
        company.setEmail("1234567@126.com");
        company.setAddress("北京市 朝阳区");
        company.setPersonName("xxx");
        companyDao.save(company);

        List<Role> roles=new ArrayList<>();
        Role role=roleDao.findOneByName("admin");
        if(Objects.isNull(role)){
            role=new Role();
        }
        role.setName("admin");
        role.setDescp("高级管理员");
        roleDao.save(role);
        roles.add(role);

        Role roleCommon=roleDao.findOneByName("common");
        if(Objects.isNull(roleCommon)){
            roleCommon=new Role();
        }
        roleCommon.setName("common");
        roleCommon.setDescp("普通操作员");
        roleDao.save(roleCommon);

        Role finance=roleDao.findOneByName("finance");
        if(Objects.isNull(finance)){
            finance=new Role();
        }
        finance.setName("finance");
        finance.setDescp("财务人员");
        roleDao.save(finance);

        Admin admin = adminDao.findOneByUsername("admin");
        if (Objects.isNull(admin)) {
            admin = new Admin();
        }
        admin.setUsername("admin");
        admin.setPassword(Md5Util.getMd5("admin"));
        admin.setCompany(company);
        admin.setRoleList(roles);
        adminDao.save(admin);


    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String gologin(Model model) {
        model.addAttribute("loginForm", new LoginForm());
        return "admin/login";
    }

    @RequestMapping(value = "/403", method = RequestMethod.GET)
    public String permissionDeny() {
        return "admin/op_error";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@Valid LoginForm loginForm,BindingResult bindingResult,Model model) {
        if (bindingResult.hasErrors()) {
            return "admin/login";
        }
        UsernamePasswordToken token = new UsernamePasswordToken(loginForm.getUsername(), Md5Util.getMd5(loginForm.getPassword()));
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.getSession().setAttribute("username", loginForm.getUsername());
        try {
            currentUser.login(token);
        } catch (AuthenticationException exception) {
            String msg="";
            if (exception instanceof UnknownAccountException) {
                msg = "用户不存在";
            } else if (exception instanceof IncorrectCredentialsException) {
                msg = "密码不正确";
            }
            model.addAttribute("msg",msg);
        }finally {
            if (currentUser.isAuthenticated()) {
                return "redirect:/admin/areaLocation/data";
            } else {
                token.clear();
                model.addAttribute("loginForm", new LoginForm());
                return "admin/login";
            }
        }
    }

    @RequestMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }
}
